import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Router, ActivatedRoute } from '@angular/router';
import { FormsModule, ReactiveFormsModule, FormBuilder, FormGroup, Validators, AbstractControl, ValidationErrors } from '@angular/forms';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { NzDatePickerModule } from 'ng-zorro-antd/date-picker';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzTableModule } from 'ng-zorro-antd/table';
import { NzInputNumberModule } from 'ng-zorro-antd/input-number';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzMessageModule } from 'ng-zorro-antd/message';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadModule } from 'ng-zorro-antd/upload';
import { NzDividerModule } from 'ng-zorro-antd/divider';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzPaginationModule } from 'ng-zorro-antd/pagination';
import { NzTagModule } from 'ng-zorro-antd/tag';
import { NzToolTipModule } from 'ng-zorro-antd/tooltip';
import { HttpClient, HttpParams } from '@angular/common/http';
import Swal from 'sweetalert2';

interface ItemData {
  id: number;
  productName: string;
  productCode: string;
  specification: string;
  unit: string;
  productType: string;
  fromWarehouseStock: number;
  toWarehouseStock: number;
  allocationQuantity: number;
  unitPrice: number;
  allocationAmount: number;
  remarks?: string;
}

@Component({
  selector: 'app-allocation-add',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    FormsModule,
    ReactiveFormsModule,
    NzFormModule,
    NzInputModule,
    NzSelectModule,
    NzDatePickerModule,
    NzButtonModule,
    NzTableModule,
    NzInputNumberModule,
    NzIconModule,
    NzMessageModule,
    NzUploadModule,
    NzDividerModule,
    NzCardModule,
    NzPaginationModule,
    NzTagModule,
    NzToolTipModule
  ],
  templateUrl: './allocation-add.component.html',
  styleUrls: ['./allocation-add.component.scss']
})
export class AllocationAddComponent implements OnInit {
  allocationForm!: FormGroup;
  listOfData: ItemData[] = [];
  editId: number | null = null;
  // 创建时间
  creationTime: string = new Date().toLocaleString();
  
  // 是否是编辑模式
  isEditMode = false;
  
  // 上传文件列表
  fileList: any[] = [];
  uploading = false;
  
  // 仓库列表
  warehouseList = [
    { value: '北京总仓', label: '北京总仓' },
    { value: '上海分仓', label: '上海分仓' },
    { value: '广州分仓', label: '广州分仓' },
    { value: '深圳分仓', label: '深圳分仓' },
    { value: '成都分仓', label: '成都分仓' },
    { value: '武汉分仓', label: '武汉分仓' }
  ];
  
  // 调拨类型
  allocationTypes = [
    { value: '货品调拨', label: '货品调拨' },
    { value: '备品调拨', label: '备品调拨' },
    { value: '样品调拨', label: '样品调拨' },
    { value: '赠品调拨', label: '赠品调拨' }
  ];
  
  // 产品类型列表
  productTypes = [
    { value: '1', label: '饮品' },
    { value: '2', label: '零食' },
    { value: '3', label: '生鲜' },
    { value: '4', label: '日用品' },
    { value: '5', label: '电子产品' }
  ];
  
  // 状态选项
  statusOptions = [
    { value: '草稿', label: '草稿' },
    { value: '待审核', label: '待审核' },
    { value: '已审核', label: '已审核' },
    { value: '已完成', label: '已完成' }
  ];
  
  // 产品列表
  productList = [
    { id: 1, name: '可口可乐', code: 'KK001', specification: '330ml', unit: '瓶', type: '1', price: 3.5 },
    { id: 2, name: '百事可乐', code: 'BS002', specification: '330ml', unit: '瓶', type: '1', price: 3.0 },
    { id: 3, name: '农夫山泉', code: 'NH003', specification: '550ml', unit: '瓶', type: '1', price: 2.0 },
    { id: 4, name: '乐事薯片', code: 'LS004', specification: '70g', unit: '袋', type: '2', price: 6.5 },
    { id: 5, name: '奥利奥饼干', code: 'ALO005', specification: '116g', unit: '包', type: '2', price: 8.0 },
    { id: 6, name: '苹果', code: 'PG006', specification: '500g', unit: '斤', type: '3', price: 10.0 },
    { id: 7, name: '香蕉', code: 'XJ007', specification: '500g', unit: '斤', type: '3', price: 6.0 },
    { id: 8, name: '洗手液', code: 'XSY008', specification: '500ml', unit: '瓶', type: '4', price: 15.0 },
    { id: 9, name: '纸巾', code: 'ZJ009', specification: '100抽', unit: '包', type: '4', price: 5.0 },
    { id: 10, name: '充电宝', code: 'CDB010', specification: '10000mAh', unit: '个', type: '5', price: 99.0 }
  ];
  
  // 经办人列表
  handlerList = [
    { value: '1', label: '李依依' },
    { value: '2', label: '张三' },
    { value: '3', label: '王五' },
    { value: '4', label: '赵六' }
  ];
  
  // 表格选择相关
  selectedRowIds: number[] = [];
  isAllSelected = false;
  isIndeterminate = false;
  total = 0;
  
  // 产品弹框相关
  showProductModal = false;
  productLoading = false;
  productSearchTerm = '';
  selectedUnit = '';
  modalProductList: any[] = [];
  selectedModalProductIds: number[] = [];
  
  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private router: Router,
    private http: HttpClient,
    private route: ActivatedRoute
  ) {}

  ngOnInit(): void {
    // 初始化表单
    this.initForm();
    
    // 设置当前日期
    const today = new Date();
    this.creationTime = today.toLocaleString();
    
    // 先检查localStorage中是否有数据 - 统一使用editAllocationData作为key
    const allocationData = localStorage.getItem('editAllocationData') || localStorage.getItem('allocationEditData');
    if (allocationData) {
      try {
        const formData = JSON.parse(allocationData);
        console.log('从localStorage获取到调拨单数据:', formData);
        
        // 删除localStorage中的数据，避免影响下次打开
        localStorage.removeItem('editAllocationData');
        localStorage.removeItem('allocationEditData');
        
        // 设置为编辑模式
        this.isEditMode = true;
        
        // 填充表单数据
        this.allocationForm.patchValue({
          allocationNo: formData.allocationNo || '',
          allocationType: formData.allocationType || '',
          applicationDate: this.formatDateForDateInput(formData.applicationDate),
          fromWarehouse: formData.fromWarehouse || '',
          toWarehouse: formData.toWarehouse || '',
          handler: formData.handler || '',
          status: formData.status || '草稿',
          remarks: formData.remarks || ''
        });
        
        console.log('设置调拨日期为:', this.formatDateForDateInput(formData.applicationDate));
        
        // 填充明细数据
        if (formData.allocationItems && formData.allocationItems.length > 0) {
          console.log('处理allocationItems数组数据,数量:', formData.allocationItems.length);
          // 将allocationItems数据映射到所需格式
          this.listOfData = formData.allocationItems.map((item: any) => ({
            id: item.id || item.productId || 0,
            productName: item.productName || '',
            productCode: item.productCode || '',
            specification: item.specification || '',
            unit: item.unit || '',
            productType: item.productType || '',
            fromWarehouseStock: item.fromWarehouseStock || item.sourceStock || 0,
            toWarehouseStock: item.toWarehouseStock || item.toStock || item.targetStock || 0, // 优先使用toStock字段
            allocationQuantity: item.allocationQuantity || 0,
            unitPrice: item.unitPrice || 0,
            allocationAmount: item.allocationAmount || 0,
            remarks: item.remarks || ''
          }));
        } 
        else if (formData.details && formData.details.length > 0) {
          console.log('处理details数组数据，数量:', formData.details.length);
          this.listOfData = formData.details;
        }
        else if (formData.items && formData.items.length > 0) {
          console.log('处理items数组数据，数量:', formData.items.length);
          this.listOfData = formData.items;
        }
        
        this.updateTotal();
        
        // 如果有附件数据，填充附件列表
        if (formData.files && formData.files.length > 0) {
          console.log('获取到文件信息:', formData.files);
          this.fileList = formData.files.map((file: any) => ({
            name: file.fileName || file.name || '',
            size: file.fileSize || file.size || 0,
            type: file.fileType || file.type || this.getFileExtension(file.fileName || file.name || ''),
            url: file.filePath || file.url || '',
            uid: file.id || this.generateUid(),
            status: 'done'
          }));
        }
        
        this.message.success('数据加载成功');
      } catch (error) {
        console.error('解析调拨单数据失败', error);
        this.message.error('解析调拨单数据失败，请重试');
      }
    } else {
      // 检查URL参数，判断是新增还是编辑模式
      this.route.paramMap.subscribe(params => {
        const id = params.get('id');
        if (id) {
          // 编辑模式，加载已有数据
          this.isEditMode = true;
          this.loadAllocationData(id);
        } else {
          // 新增模式，生成调拨单号
          this.isEditMode = false;
        }
      });
    }
    
    // 预加载模拟产品数据
    this.loadMockProducts();
  }
  // 加载调拨单数据
  loadAllocationData(id: string): void {
    // 确保ID有效
    if (!id) {
      this.message.error('无效的调拨单ID,无法加载数据');
      setTimeout(() => {
        this.router.navigate(['/business/inventory/allocation']);
      }, 1500);
      return;
    }
    
    // 设置为编辑模式
    this.isEditMode = true;
    
    // 显示加载状态
    this.message.loading('正在加载数据...');
    
    // 通过API获取数据
    this.http.get<any>(`https://localhost:44350/api/app/allocation/${id}`)
      .subscribe({
        next: (response: any) => {
          if (response) {
            console.log('API返回的调拨单数据:', response);
            
            // 填充表单数据
            this.allocationForm.patchValue({
              allocationNo: response.allocationNo || '',
              allocationType: response.allocationType || '',
              applicationDate: this.formatDateForDateInput(response.applicationDate),
              fromWarehouse: response.fromWarehouse || '',
              toWarehouse: response.toWarehouse || '',
              handler: response.handler || '',
              status: response.status || '草稿',
              remarks: response.remarks || ''
            });
            
            console.log('从API加载数据，设置调拨日期为:', this.formatDateForDateInput(response.applicationDate));
            
            // 填充明细数据
            if (response.allocationItems && response.allocationItems.length > 0) {
              console.log('处理allocationItems数组数据，数量:', response.allocationItems.length);
              // 将allocationItems数据映射到所需格式
              this.listOfData = response.allocationItems.map((item: any) => ({
                id: item.id || item.productId || 0,
                productName: item.productName || '',
                productCode: item.productCode || '',
                specification: item.specification || '',
                unit: item.unit || '',
                productType: item.productType || '',
                fromWarehouseStock: item.fromWarehouseStock || item.sourceStock || 0,
                toWarehouseStock: item.toWarehouseStock || item.toStock || item.targetStock || 0, // 优先使用toStock字段
                allocationQuantity: item.allocationQuantity || 0,
                unitPrice: item.unitPrice || 0,
                allocationAmount: item.allocationAmount || 0,
                remarks: item.remarks || ''
              }));
            }
            else if (response.details && response.details.length > 0) {
              console.log('处理details数组数据，数量:', response.details.length);
              this.listOfData = response.details;
            } else if (response.items && response.items.length > 0) {
              console.log('处理items数组数据，数量:', response.items.length);
              this.listOfData = response.items;
            } else {
              // 如果没有明细数据，创建一个空行
              this.addRow();
            }
            
            this.updateTotal();
            
            // 如果有附件数据，填充附件列表
            if (response.files && response.files.length > 0) {
              console.log('获取到文件信息:', response.files);
              this.fileList = response.files.map((file: any) => ({
                name: file.fileName || file.name || '',
                size: file.fileSize || file.size || 0,
                type: file.fileType || file.type || this.getFileExtension(file.fileName || file.name || ''),
                url: file.filePath || file.url || '',
                uid: file.id || this.generateUid(),
                status: 'done'
              }));
            }
            
            this.message.success('数据加载成功');
          } else {
            this.message.warning('未找到调拨单数据');
          }
        },
        error: (error) => {
          console.error('加载调拨单数据失败:', error);
          this.message.error('加载调拨单数据失败: ' + (error.error?.message || '未知错误'));
        }
      });
  }

  // 移除仓库验证器
  warehouseValidator = (control: AbstractControl): ValidationErrors | null => {
    const fromWarehouse = this.allocationForm?.get('fromWarehouse')?.value;
    const toWarehouse = this.allocationForm?.get('toWarehouse')?.value;
    
    if (fromWarehouse && toWarehouse && fromWarehouse === toWarehouse) {
      return { sameWarehouse: true };
    }
    return null;
  };

  initForm(): void {
    this.allocationForm = this.fb.group({
      allocationNo: [{ value: '', disabled: true }],
      allocationType: ['', [Validators.required]],
      applicationDate: [this.formatDateForDateInput(new Date()), [Validators.required]],
      fromWarehouse: ['', [Validators.required]],
      toWarehouse: ['', [Validators.required]],
      handler: ['李依依', [Validators.required]],
      status: ['草稿', [Validators.required]],
      remarks: ['']
    });

    // 添加值变更监听器来触发验证
    this.allocationForm.get('fromWarehouse')?.valueChanges.subscribe(() => {
      // 只在两个都有值时进行检查
      const fromWarehouse = this.allocationForm.get('fromWarehouse')?.value;
      const toWarehouse = this.allocationForm.get('toWarehouse')?.value;
      
      if (fromWarehouse && toWarehouse && fromWarehouse === toWarehouse) {
        this.showWarehouseAlert();
      }
    });

    this.allocationForm.get('toWarehouse')?.valueChanges.subscribe((value) => {
      // 只在两个都有值时进行检查
      const fromWarehouse = this.allocationForm.get('fromWarehouse')?.value;
      
      if (fromWarehouse && value && fromWarehouse === value) {
        this.showWarehouseAlert();
      }
    });
  }

  // 显示仓库警告弹窗
  showWarehouseAlert(): void {
    // 使用NG-ZORRO消息服务创建警告提示
    this.message.warning('入库仓库和出库仓库不能为同一个仓库！', {
      nzDuration: 3000,
      nzPauseOnHover: true
    });
    
    // 清除调入仓库的值
    this.allocationForm.get('toWarehouse')?.setValue('');
  }

  // 验证仓库选择 (保留但修改逻辑，不再设置表单错误)
  validateWarehouses(): void {
    const fromWarehouse = this.allocationForm.get('fromWarehouse')?.value;
    const toWarehouse = this.allocationForm.get('toWarehouse')?.value;
    
    if (fromWarehouse && toWarehouse && fromWarehouse === toWarehouse) {
      this.showWarehouseAlert();
    }
  }

  // 添加行
  addRow(): void {
    const newId = this.listOfData.length > 0 ? Math.max(...this.listOfData.map(item => item.id)) + 1 : 1;
    this.listOfData = [
      ...this.listOfData,
      {
        id: newId,
        productName: '',
        productCode: '',
        specification: '',
        unit: '个',
        productType: '',
        fromWarehouseStock: 0,
        toWarehouseStock: 0,
        allocationQuantity: 0,
        unitPrice: 0,
        allocationAmount: 0
      }
    ];
    this.editId = newId;
    this.updateTotal();
  }

  // 删除行
  deleteRow(id: number): void {
    this.listOfData = this.listOfData.filter(d => d.id !== id);
    this.updateTotal();
  }

  // 更新总数
  updateTotal(): void {
    this.total = this.listOfData.length;
  }

  // 获取当前页数据
  get pagedData(): ItemData[] {
    return this.listOfData;
  }

  // 计算金额
  calculateAmount(data: ItemData): void {
    // 检查调拨数量是否为0或负数
    if (data.allocationQuantity <= 0) {
      // 显示错误提示
      Swal.fire({
        icon: 'error',
        title: '货品数量必须大于0!',
        showConfirmButton: false,
        timer: 2000,
        position: 'top'
      });
      // 重置数量为空
      data.allocationQuantity = null as any;
      return;
    }
    
    // 计算金额
    data.allocationAmount = data.allocationQuantity * data.unitPrice;
  }

  // 选择产品时自动填充数据
  onProductSelected(productName: string, rowData: any): void {
    if (productName) {
      const selectedProduct = this.productList.find(p => p.name === productName);
      if (selectedProduct) {
        rowData.productCode = selectedProduct.code;
        rowData.specification = selectedProduct.specification;
        rowData.unit = selectedProduct.unit;
        rowData.productType = this.productTypes.find(t => t.value === selectedProduct.type)?.label || '';
        rowData.unitPrice = selectedProduct.price;
        
        // 模拟获取库存数据
        rowData.fromWarehouseStock = Math.floor(Math.random() * 100) + 10;
        rowData.toWarehouseStock = Math.floor(Math.random() * 50) + 5;
        
        this.calculateAmount(rowData);
      }
    }
  }

  // 计算总数量
  get totalQuantity(): number {
    return this.listOfData.reduce((sum, item) => sum + (item.allocationQuantity || 0), 0);
  }

  // 计算总金额
  get totalAmount(): number {
    return this.listOfData.reduce((sum, item) => sum + (item.allocationAmount || 0), 0);
  }

  // 开始编辑
  startEdit(id: number): void {
    this.editId = id;
  }

  // 获取状态标签颜色
  getStatusColor(status: string): string {
    switch (status) {
      case '草稿':
        return 'blue';
      case '待审核':
        return 'orange';
      case '已审核':
        return 'green';
      case '已完成':
        return 'green';
      default:
        return 'default';
    }
  }

  // 获取状态徽章样式类
  getStatusBadgeClass(status: string): string {
    switch (status) {
      case '草稿':
        return 'bg-primary';
      case '待审核':
        return 'bg-warning';
      case '驳回':
        return 'bg-danger';
      case '已审核':
      case '通过':
        return 'bg-success';
      case '已完成':
        return 'bg-success';
      default:
        return 'bg-secondary';
    }
  }

  // 保存表单
  saveForm(): void {
    if (this.allocationForm.invalid) {
      Object.values(this.allocationForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
      
      this.message.error('表单填写有误，请检查！');
      return;
    }
    
    // 再次检查调入调出仓库是否相同
    const fromWarehouse = this.allocationForm.get('fromWarehouse')?.value;
    const toWarehouse = this.allocationForm.get('toWarehouse')?.value;
    if (fromWarehouse && toWarehouse && fromWarehouse === toWarehouse) {
      this.showWarehouseAlert();
      return;
    }
    
    if (this.listOfData.length === 0) {
      this.message.error('请添加调拨明细！');
      return;
    }
    
    // 检查明细数据
    const invalidItems = this.listOfData.filter(item => !item.productName || !item.allocationQuantity);
    if (invalidItems.length > 0) {
      this.message.error('明细数据不完整，请检查！');
      return;
    }
    
    // 检查调拨数量是否为零或负数
    const zeroQuantityItems = this.listOfData.filter(item => item.allocationQuantity <= 0);
    if (zeroQuantityItems.length > 0) {
      // 显示错误提示
      Swal.fire({
        icon: 'error',
        title: '货品数量必须大于0!',
        showConfirmButton: false,
        timer: 2000,
        position: 'top'
      });
      return;
    }
    
    // 提交表单
    const formValue = this.allocationForm.getRawValue();
    const allocationData = {
      allocationType: formValue.allocationType || '',
      allocationNo: formValue.allocationNo || '',
      applicationDate: formValue.applicationDate || new Date(),
      fromWarehouse: formValue.fromWarehouse || '',
      toWarehouse: formValue.toWarehouse || '',
      handler: formValue.handler || '',
      remarks: formValue.remarks || '',
      status: formValue.status || '草稿',
      singer: formValue.handler || '', // 签名人使用经办人
      details: this.listOfData.map(item => ({
        productId: item.id || 0, // 添加产品ID
        productName: item.productName || '',
        productCode: item.productCode || '',
        specification: item.specification || '',
        unit: item.unit || '',
        productType: item.productType || '',
        fromWarehouseStock: Number(item.fromWarehouseStock || 0),
        toWarehouseStock: Number(item.toWarehouseStock || 0),
        allocationQuantity: Number(item.allocationQuantity || 0),
        unitPrice: Number(item.unitPrice || 0),
        allocationAmount: Number(item.allocationAmount || 0),
        remarks: item.remarks || ''
      })),
      files: this.prepareFileData(this.fileList)
    };
    
    console.log('提交的调拨单数据：', allocationData);
    
    // 显示加载状态
    this.message.loading('正在保存调拨单...');
    
    // 检查是否为编辑模式
    this.route.paramMap.subscribe(params => {
      const id = params.get('id');
      
      // 根据是否有ID决定是新增还是编辑
      if (id) {
        // 编辑模式，调用PUT接口
        this.http.put(`https://localhost:44350/api/app/allocation/${id}`, allocationData)
          .subscribe({
            next: (response: any) => {
              console.log('更新成功：', response);
              // 使用SweetAlert2显示居中弹框
              Swal.fire({
                icon: 'success',
                title: '调拨单更新成功！',
                confirmButtonText: '确定',
                confirmButtonColor: '#1890ff'
              }).then((result) => {
                if (result.isConfirmed) {
                  this.router.navigate(['/business/inventory/allocation']);
                }
              });
            },
            error: (error) => {
              console.error('更新失败：', error);
              this.message.error('更新失败：' + (error.error?.message || '未知错误'));
            }
          });
      } else {
        // 新增模式，调用POST接口
        this.http.post('https://localhost:44350/api/app/allocation', allocationData)
          .subscribe({
            next: (response: any) => {
              console.log('保存成功：', response);
              // 使用SweetAlert2显示居中弹框
              Swal.fire({
                icon: 'success',
                title: '调拨单保存成功！',
                confirmButtonText: '确定',
                confirmButtonColor: '#1890ff'
              }).then((result) => {
                if (result.isConfirmed) {
                  this.router.navigate(['/business/inventory/allocation']);
                }
              });
            },
            error: (error) => {
              console.error('保存失败：', error);
              this.message.error('保存失败：' + (error.error?.message || '未知错误'));
            }
          });
      }
    });
  }
  
  // 取消操作
  cancel(): void {
    this.router.navigate(['/inventory/allocation']);
  }
  
  // 上传前检查
  beforeUpload = (file: any): boolean => {
    this.fileList = [...this.fileList, file];
    return false;
  };
  
  // 处理文件上传
  handleFileUpload(event: any): void {
    const files = event.target.files;
    if (files) {
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        // 检查文件大小（200MB限制）
        if (file.size > 200 * 1024 * 1024) {
          this.message.error(`文件 ${file.name} 超过200MB限制，无法上传`);
          continue;
        }
        
        // 添加文件到列表
        this.fileList.push({
          name: file.name,
          size: file.size,
          type: file.type,
          lastModified: file.lastModified,
          file: file // 保存原始文件对象，用于后续上传
        });
      }
    }
  }
  
  // 删除文件
  removeFile(file: any): void {
    this.fileList = this.fileList.filter(item => item.name !== file.name || item.size !== file.size);
  }
  
  // 获取文件扩展名
  getFileExtension(filename: string): string {
    return filename.split('.').pop() || '';
  }
  
  // 生成唯一ID
  generateUid(): string {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
  }
  
  // 生成符合System.Guid格式的UUID
  generateUUID(): string {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      const r = Math.random() * 16 | 0;
      const v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }
  
  // 验证是否为有效的Guid格式
  isValidGuid(id: string): boolean {
    if (!id) return false;
    const guidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
    return guidRegex.test(id);
  }
  
  // 准备文件数据，确保ID格式正确
  prepareFileData(files: any[]): any[] {
    return files.map(file => {
      // 准备文件数据
      const fileData = {
        fileName: file.name || '',
        fileType: file.fileType || this.getFileExtension(file.name || ''),
        fileSize: file.size || 0,
        filePath: file.url || `/uploads/allocation/${new Date().getFullYear()}/${(new Date().getMonth() + 1).toString().padStart(2, '0')}/${file.name || 'unnamed'}`,
        businessType: file.businessType || '调拨单',
        // 确保文件ID格式正确
        id: file.id || file.uid
      };
      
      // 检查ID是否为有效的Guid格式
      if (!fileData.id || !this.isValidGuid(fileData.id)) {
        fileData.id = this.generateUUID();
      }
      
      return fileData;
    });
  }

  // 选择项目
  isItemSelected(id: number): boolean {
    return this.selectedRowIds.includes(id);
  }
  
  // 选择/取消选择项目
  onItemChecked(id: number, checked: boolean): void {
    if (checked) {
      this.selectedRowIds = [...this.selectedRowIds, id];
    } else {
      this.selectedRowIds = this.selectedRowIds.filter(itemId => itemId !== id);
    }
    this.refreshCheckStatus();
  }
  
  // 全选/取消全选
  onAllChecked(checked: boolean): void {
    if (checked) {
      this.selectedRowIds = this.listOfData.map(item => item.id);
    } else {
      this.selectedRowIds = [];
    }
    this.refreshCheckStatus();
  }
  
  // 刷新选择状态
  refreshCheckStatus(): void {
    this.isAllSelected = this.listOfData.length > 0 && this.selectedRowIds.length === this.listOfData.length;
    this.isIndeterminate = this.selectedRowIds.length > 0 && this.selectedRowIds.length < this.listOfData.length;
  }
  
  // 批量删除
  batchDeleteRows(): void {
    if (this.selectedRowIds.length === 0) {
      return;
    }
    
    this.listOfData = this.listOfData.filter(item => !this.selectedRowIds.includes(item.id));
    this.selectedRowIds = [];
    this.refreshCheckStatus();
    this.updateTotal();
  }

  // 打开产品选择弹框
  openProductModal(): void {
    // 获取选中的出库仓库和入库仓库
    const fromWarehouse = this.allocationForm.get('fromWarehouse')?.value;
    const toWarehouse = this.allocationForm.get('toWarehouse')?.value;
    
    // 如果仓库未选择，显示提示信息并返回，不打开产品弹框
    if (!fromWarehouse || !toWarehouse) {
      this.message.warning('请先选择调出仓库和调入仓库', {
        nzDuration: 3000,
        nzPauseOnHover: true,
        // 确保消息显示在最上层
        nzAnimate: true
      });
      return;
    }
    
    this.showProductModal = true;
    this.productLoading = true;
    this.selectedModalProductIds = [];
    
    // 构建API请求参数，包含仓库信息
    let url = 'https://localhost:44350/api/app/product-item';
    url += `?warehouseCode=${fromWarehouse}&targetWarehouseCode=${toWarehouse}`;
    
    // 调用API获取产品列表
    this.http.get(url)
      .subscribe(
        (response: any) => {
          // 假设API返回的数据格式为 { items: [...产品列表] }
          if (response && response.items) {
            this.modalProductList = response.items.map((p: any) => ({
              id: p.id,
              productCode: p.productCode || '',
              productName: p.productName,
              specification: p.specification,
              unit: p.unit,
              purchasePrice: p.purchasePrice,
              currentStock: p.currentStock || 0,
              // 保存仓库库存信息(如果有)
              sourceStock: p.sourceStock || p.currentStock || 0,
              targetStock: p.targetStock || 0,
              toStock: p.toStock || p.targetStock || 0 // 添加toStock字段
            }));
            console.log('获取到产品列表:', this.modalProductList);
          } else {
            this.modalProductList = [];
          }
          this.productLoading = false;
        },
        (error) => {
          console.error('获取产品列表失败:', error);
          this.message.error('获取产品列表失败: ' + (error.error?.message || '服务器错误，请稍后重试'));
          this.productLoading = false;
          this.modalProductList = [];
        }
      );
  }
  
  // 关闭产品选择弹框
  closeProductModal(): void {
    this.showProductModal = false;
    this.productSearchTerm = '';
    this.selectedUnit = '';
  }
  
  // 搜索产品
  searchProducts(): void {
    this.productLoading = true;
    
    // 获取选中的出库仓库和入库仓库
    const fromWarehouse = this.allocationForm.get('fromWarehouse')?.value;
    const toWarehouse = this.allocationForm.get('toWarehouse')?.value;
    
    // 构建查询参数
    let params = new HttpParams();
    if (this.productSearchTerm) {
      params = params.append('filter', this.productSearchTerm);
    }
    if (this.selectedUnit) {
      params = params.append('unit', this.selectedUnit);
    }
    // 添加仓库参数
    if (fromWarehouse) {
      params = params.append('warehouseCode', fromWarehouse);
    }
    if (toWarehouse) {
      params = params.append('targetWarehouseCode', toWarehouse);
    }
    
    // 调用API获取产品列表
    this.http.get('https://localhost:44350/api/app/product-item', { params })
      .subscribe({
        next: (response: any) => {
          if (response && response.items) {
            this.modalProductList = response.items.map((item: any) => ({
              id: item.id,
              productName: item.productName || item.name,
              productCode: item.productCode || item.code,
              specification: item.specification,
              unit: item.unit,
              productType: item.productType || item.type,
              purchasePrice: item.purchasePrice || 0,
              currentStock: item.currentStock || 0,
              // 保存仓库库存信息(如果有)
              sourceStock: item.sourceStock || item.currentStock || 0,
              targetStock: item.targetStock || 0,
              toStock: item.toStock || item.targetStock || 0 // 添加toStock字段
            }));
          } else {
            this.modalProductList = [];
          }
          this.productLoading = false;
        },
        error: (error) => {
          console.error('获取产品列表失败:', error);
          this.message.error('获取产品列表失败: ' + (error.error?.message || '服务器错误'));
          this.productLoading = false;
          
          // 加载失败时使用模拟数据
          this.loadMockProducts();
        }
      });
  }
  
  // 加载产品数据
  loadMockProducts(): void {
    this.productLoading = true;
    
    // 获取选中的出库仓库和入库仓库
    const fromWarehouse = this.allocationForm.get('fromWarehouse')?.value;
    const toWarehouse = this.allocationForm.get('toWarehouse')?.value;
    
    // 构建API请求URL，包含仓库信息
    let url = 'https://localhost:44350/api/app/goods-app-servicezmy';
    let params = new HttpParams();
    if (fromWarehouse) {
      params = params.append('warehouseCode', fromWarehouse);
    }
    if (toWarehouse) {
      params = params.append('targetWarehouseCode', toWarehouse);
    }
    
    // 调用API获取产品数据
    this.http.get<any>(url, { params })
      .subscribe({
        next: (response: any) => {
          if (response && response.items) {
            this.modalProductList = response.items.map((item: any) => ({
              id: item.id,
              merchandiseNo: item.merchandiseNo || item.code,
              merchandiseName: item.merchandiseName || item.name,
              merchandiseModel: item.merchandiseModel,
              merchandiseUnit: item.merchandiseUnit,
              productType: item.productType || item.type,
              merchandiseINPrice: item.merchandiseINPrice || 0,
              merchandiseIN: item.merchandiseIN || 0,
              // 保存仓库库存信息(如果有)
              sourceStock: item.sourceStock || item.currentStock || 0,
              targetStock: item.targetStock || 0,
              toStock: item.toStock || item.targetStock || 0 // 添加toStock字段
            }));
          } else {
            this.modalProductList = [];
          }
          this.productLoading = false;
        },
        error: (error) => {
          console.error('获取产品数据失败:', error);
          this.message.error('获取产品数据失败: ' + (error.error?.message || '未知错误'));
          this.productLoading = false;
          this.modalProductList = [];
        }
      });
  }
  
  // 重置产品搜索
  resetProductSearch(): void {
    this.productSearchTerm = '';
    this.selectedUnit = '';
    this.loadMockProducts();
  }
  
  // 检查是否选中所有弹框中的产品
  isAllModalProductsSelected(): boolean {
    return this.modalProductList.length > 0 && 
      this.selectedModalProductIds.length === this.modalProductList.length;
  }
  
  // 选择/取消选择所有弹框中的产品
  toggleSelectAllModalProducts(event: any): void {
    if (event.target.checked) {
      this.selectedModalProductIds = this.modalProductList.map(item => item.id);
    } else {
      this.selectedModalProductIds = [];
    }
  }
  
  // 检查弹框中的产品是否被选中
  isModalProductSelected(id: number): boolean {
    return this.selectedModalProductIds.includes(id);
  }
  
  // 选择/取消选择弹框中的产品
  toggleSelectModalProduct(id: number): void {
    if (this.selectedModalProductIds.includes(id)) {
      this.selectedModalProductIds = this.selectedModalProductIds.filter(itemId => itemId !== id);
    } else {
      this.selectedModalProductIds = [...this.selectedModalProductIds, id];
    }
  }
  
  // 确认添加产品
  confirmAddProducts(): void {
    // 获取选中的出库仓库和入库仓库
    const fromWarehouse = this.allocationForm.get('fromWarehouse')?.value;
    const toWarehouse = this.allocationForm.get('toWarehouse')?.value;
    
    if (!fromWarehouse || !toWarehouse) {
      this.message.warning('请先选择调出仓库和调入仓库', {
        nzDuration: 3000,
        nzPauseOnHover: true,
        // 确保消息显示在最上层
        nzAnimate: true
      });
      return;
    }
    
    const selectedProducts = this.modalProductList.filter(product => this.selectedModalProductIds.includes(product.id));
    
    if (selectedProducts.length === 0) {
      this.message.warning('请至少选择一个产品');
      return;
    }
    
    // 显示加载状态
    this.message.loading('正在加载库存数据...', { nzDuration: 500 });
    
    // 标记是否需要获取库存数据
    let needStockData = false;
    
    // 将选择的产品添加到调拨明细表格中
    selectedProducts.forEach(product => {
      // 检查是否已经添加过该产品
      const existingIndex = this.listOfData.findIndex(item => item.id === product.id);
      
      if (existingIndex === -1) {
        // 检查产品是否已有库存信息
        if (product.sourceStock !== undefined && (product.targetStock !== undefined || product.toStock !== undefined)) {
          // 使用产品中已有的库存数据
          this.listOfData.push({
            id: product.id,
            productName: product.productName,
            productCode: product.productCode,
            specification: product.specification,
            unit: product.unit,
            productType: product.productType || '普通商品',
            fromWarehouseStock: product.sourceStock || product.currentStock || 0,
            toWarehouseStock: product.toStock || product.targetStock || 0, // 优先使用toStock字段
            allocationQuantity: 0,
            unitPrice: product.purchasePrice || 0,
            allocationAmount: 0,
            remarks: ''
          });
          this.updateTotal();
        } else {
          // 需要获取库存数据
          needStockData = true;
          
          // 使用API获取仓库的库存数据
          this.http.get<any>(`https://localhost:44350/api/app/inventory/stock?productId=${product.id}&warehouseCode=${fromWarehouse}&targetWarehouseCode=${toWarehouse}`)
            .subscribe({
              next: (response: any) => {
                console.log('获取到库存数据:', response);
                // 添加新产品并设置库存数据
                this.listOfData.push({
                  id: product.id,
                  productName: product.productName,
                  productCode: product.productCode,
                  specification: product.specification,
                  unit: product.unit,
                  productType: product.productType || '普通商品',
                  fromWarehouseStock: response?.sourceStock || product.currentStock || 0,
                  toWarehouseStock: response?.toStock || response?.targetStock || 0, // 优先使用toStock字段
                  allocationQuantity: 0,
                  unitPrice: product.purchasePrice || 0,
                  allocationAmount: 0,
                  remarks: ''
                });
                this.updateTotal();
              },
              error: (error) => {
                console.error('获取库存数据失败:', error);
                console.log('使用产品当前库存作为调出仓库库存:', product.currentStock);
                // 添加产品，使用产品本身的库存数据
                this.listOfData.push({
                  id: product.id,
                  productName: product.productName,
                  productCode: product.productCode,
                  specification: product.specification,
                  unit: product.unit,
                  productType: product.productType || '普通商品',
                  fromWarehouseStock: product.currentStock || 0,  // 使用产品本身的库存数据
                  toWarehouseStock: product.toStock || 0, // 使用toStock字段，如果存在
                  allocationQuantity: 0,
                  unitPrice: product.purchasePrice || 0,
                  allocationAmount: 0,
                  remarks: ''
                });
                this.updateTotal();
              }
            });
        }
      }
    });
    
    // 如果不需要获取库存数据，显示成功消息
    if (!needStockData) {
      this.message.success('产品添加成功');
    }
    
    // 重新计算总数和总金额
    this.updateTotal();
    
    // 关闭弹窗
    this.closeProductModal();
  }

  // 格式化日期为YYYY-MM-DD
  formatDateForDateInput(date: string | Date): string {
    if (!date) {
      return '';
    }
    const d = new Date(date);
    let month = '' + (d.getMonth() + 1);
    let day = '' + d.getDate();
    const year = d.getFullYear();

    if (month.length < 2)
      month = '0' + month;
    if (day.length < 2)
      day = '0' + day;

    return [year, month, day].join('-');
  }
} 